<?php
/**
 * Created by PhpStrom
 * User: 郭碧云
 * Date: 2021/3/30 10:44
 * Desc:
 */

namespace App\Service;


use App\Lib\Common;
use App\Models\Admin\ModelHasRoles;
use App\Models\Admin\Org;
use App\Models\Admin\PermissionOrg;

class OrgService extends BaseService {
    protected $modelName="Admin.Org";
    //组织机构列表(select组件中使用)
    public function orgList($where,$file="*") {
        //查询
        $data = $this->getOrgData($where,$file);
        //字段处理
        foreach ($data as $key => $d) {
            $data[$key]["name"]="[".$d["id"]."] ".$d["name"];
        }
        return Common::getTree($data);
    }


    /**
     * 获取组织机构管理范围
     * @param $where 查询条件
     * @param $field 查询的字段，默认为 "*" 查询指定字段输入数组[filed1,filed2,filed3,...]
     */
    public function getOrgData($where,$filed="*") {
        $orgs = (new PermissionOrg())->where("user_id", getCurrentUser()['id'])->pluck('org_id');
        $orgs = !empty($orgs) ? $orgs->toArray() : [getCurrentUser()['org_id']];
        //是否是站点管理员
        $isSite = (new ModelHasRoles())->isStieRole(getCurrentUser()['id'])->toArray();
        //查询
        $data = (new Org())->getList($filed,$where, $isSite, $orgs);
        //非站点管理员整理组织机构数据
        if (empty($isSite)) {
            //获取全部组织机构
            $all = (new Org())->orderBy("sort", "asc")->get($filed)->toArray();
            $father = Common::father_list($data, $all);
            $data = array_unique(array_merge($data, $father), SORT_REGULAR);
            //不在分管范围的需要添加禁止字段
            return $this->addDisabled($data, $orgs);
        }
        return $data;
    }

    //添加禁止字段
    protected function addDisabled($data, $orgs) {
        foreach ($data as $k => $d) {
            if (!in_array($d['id'], $orgs)) {
                $data[$k]['disabled'] = true;
            }
        }
        return $data;
    }

    /**
     * 获取父类栏目
     * @param $id 父栏目id
     */
    public function getParent($id) {
        if ($id > 0) {
            $result = (new Org())->withoutGlobalScope('site_id_scope')->find($id)->toArray();
        } else {
            $result = (new Org())->where("name", "全站")->first()->toArray();
        }
        return $result;
    }

    /**
     * 添加
     * @param $params 需要添加的参数数组
     */
    public function add($params) {
        //限制节点下不重复
        $repeate = (new Org())->repeate($params);
        if (!empty($repeate)) {
            return ['error' => 70002, 'msg' => '该部门下已存在相同机构'];
        }
        //获取插入数据
        $data = $this->getData($params);
        //保存
        $result = (new Org())->create($data)->toArray();
        if (!empty($result)) {
            //更新父类子级数量
            $this->updateChildNum($result["parent_id"]);
            //更新code
            $this->updateCode($result);
            return ['error' => 0, 'msg' => "添加成功"];
        }
        return ['error' => 70000, 'msg' => '添加失败'];
    }

    /**
     * 更新code
     */
    public function updateCode($params) {
        return (new Org())->where("id", $params['id'])->update(["code" => $params['code'] . $params['id'] . "."]);
    }

    /**
     * 更新父节点管理机构数量--自增
     * @param $parent_id 父组织id
     */
    public function updateChildNum($parent_id) {
        (new Org())->where("id", $parent_id)->increment('children_num');
    }

    /**
     * 更新父节点管理机构数量--自减
     * @param $parent_id 父组织id
     */
    public function updateChildNumDes($parent_id) {
        (new Org())->where("id", $parent_id)->decrement('children_num');
    }


    /**
     * 更新数据
     */
    public function updateInfo($params, $id) {
        //组织机构的旧信息
        $oldInfo = (new Org())->find($id)->toArray();
        if (empty($oldInfo)) {
            return ["error" => 70000, "msg" => "更新数据不存在"];
        }
        //查找旧父栏目
        if ($oldInfo["parent_id"] == 0) {
            $oldFather = (new Org())->where("parent_id", 0)->where("site_id", getCurrentSiteId())->first()->toArray();
        } else {
            $oldFather = (new Org())->find($oldInfo["parent_id"])->toArray();
        }
        //父栏目改变时
        if ($params["parent_id"] != $oldFather["id"]) {
            //移动组织下是否有子部门
            if ($oldInfo["children_num"] > 0) {
                return ["error" => 80003, "msg" => "该组织机构含有子部门，请先移除子部门在移动该组织机构"];
            }
            //更改变父栏目时，改变旧父栏目的子栏目数目
            (new Org())->where("id", $oldFather["id"])->decrement('children_num');
            //更改变父栏目时，改变新父栏目的子栏目数目，子组织的深度及编码
            $this->updateChildNum($params["parent_id"]);
        }
        //更新数据
        $params = $this->getData($params);
        $params["code"] = $params["code"] . $id;
        $result = (new Org())->where("id", $id)->update($params);
        return !$result ? ["error" => 80000, "msg" => "更新失败"] : ["error" => 0, "data" => $params];
    }

    /**
     * 获取一条组织机构
     * @param $id 组织id
     */
    public function getInfo($id) {
        if ($id == 0) {
            return [
                "id" => 0,
                "name" => "全站",
                "parent_id" => 0,
            ];
        }
        $result = (new Org())->find($id);
        if (empty($result)) {
            return [];
        }
        return $result->toArray();
    }

    /**
     * 获取添加数组
     * @param $data 需要整理的数组
     */
    private function getData($params) {
        //寻找parent_id的层级，新层级自动加1
        $parentInfo = (new Org())->getInfo($params["parent_id"]);
        $params["depth"] = $parentInfo["depth"] + 1;
        $params["code"] = $parentInfo["code"];
        $params["site_id"] = getCurrentSiteId();
        $params["description"] = null == $params["description"] || "" == $params["description"] || empty($params["description"]) ? "" : $params["description"];
        $params["sort"] = null == $params["sort"] || "" == $params["sort"] || empty($params["sort"]) ? 0 : $params["sort"];
        $params["creator"] = getCurrentUser()["id"];
        return $params;
    }

    //删除机构
    public function delete($id) {
        $oldInfo = (new Org())->getInfo($id);
        if ($oldInfo["children_num"] > 0) {
            return ['error' => 80003, 'msg' => "含有子部门，不可删除"];
        }
        //删除
        $result = (new Org())->where("id", $id)->delete();
        if (!$result) {
            return ['error' => 80001, 'msg' => '删除失败'];
        }
        //更改父类子数目
        (new OrgService())->updateChildNumDes($oldInfo['parent_id']);
        return ['error' => 0, 'msg' => '删除成功'];
    }

    /**
     * 排序
     */
    public function setSort($id, $sort) {
        return (new Org())->where("id", $id)->update(["sort" => $sort]);
    }
}
